package org.millioncall.yueyoga.common;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.ModelMap;

/**
 * 公共服务类
 * 
 * @author zangjinyu
 * 
 */
public class GlobalService {
	public static void initBasicData(HttpServletRequest request, ModelMap model) {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + path + "/";
		model.put("basePath", basePath);// 项目基路径
		model.put("viewPath", GlobalConstants.APP_VIEW_PATH);// 视图基路径
		model.put("assetsPath", GlobalConstants.ASSETS_PATH);
		model.put("resourcePath", GlobalConstants.RESOURCE_PATH);
		model.put("padResourcePath", GlobalConstants.PAD_RESOURCE_PATH);
	}

	/**
	 * 将异常堆栈转变为字符串
	 * 
	 * @param ex
	 * @return
	 */
	public static String buildStringOfException(Throwable ex) {
		StringBuilder sb = new StringBuilder();
		sb.append(ex);
		StackTraceElement[] trace = ex.getStackTrace();

		for (StackTraceElement traceElement : trace) {
			sb.append("\n\tat " + traceElement);
		}

		for (Throwable se : ex.getSuppressed()) {
			sb.append(buildStringOfEnclosedStackTrace(se, trace, "Suppressed:",
					"\t") + "\n");
		}

		Throwable cause = ex.getCause();
		if (cause != null) {
			sb.append(buildStringOfEnclosedStackTrace(cause, trace,
					"Caused by:", ""));
		}
		return sb.toString();
	}

	private static String buildStringOfEnclosedStackTrace(Throwable se,
			StackTraceElement[] enclosingTrace, String caption, String prefix) {

		StringBuilder sb = new StringBuilder();

		StackTraceElement[] trace = se.getStackTrace();
		int m = trace.length - 1;
		int n = enclosingTrace.length - 1;
		while (m >= 0 && n >= 0 && trace[m].equals(enclosingTrace[n])) {
			m--;
			n--;
		}
		int framesInCommon = trace.length - 1 - m;

		sb.append(prefix + caption + se + "\n");

		for (int i = 0; i <= m; i++) {
			sb.append(prefix + "\n\tat " + trace[i] + "\n");
		}

		if (framesInCommon != 0) {
			sb.append(prefix + "\t... " + framesInCommon + " more\n");
		}

		for (Throwable t : se.getSuppressed()) {
			sb.append(buildStringOfEnclosedStackTrace(t, trace, "Suppressed:",
					prefix + "\t") + "\n");
		}

		Throwable cause = se.getCause();
		if (cause != null) {
			sb.append(buildStringOfEnclosedStackTrace(cause, trace,
					"Caused by:", prefix) + "\n");
		}
		return sb.toString();
	}
}
